import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'

import { PageService } from '@shared/services/page.service'
import { ETabScrollStatus } from '@shared/enums'
import { CommonAcquirerService } from '@shared/services/acquirer.service'
import { DetailTabClass } from '@shared/classes/DetailTabClass'
import { Settle, IUpdateAcquirerSettlement } from '@shared/interfaces/acquirer'
import { AcquirerService } from '../../acquirer.service'
import { ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { deepCopy } from '@delon/util'
import { I18NService } from '@core'

@Component({
  selector: 'app-acquirer-detail-tab-settlement',
  templateUrl: './tab-settlement.component.html',
  styleUrls: ['../../../../shared/components/base-info/base-info.component.less']
})
export class AcquirerDetailTabSettlementComponent extends DetailTabClass<Settle> implements OnInit {

  @ViewChild('chkSettlement') chkSettlement: TemplateRef<any>
  @ViewChild('settleOperate') settleOperate: TemplateRef<any>

  params: IUpdateAcquirerSettlement = {
    version: 0,
    settlement: {reportList: []}
  }
  settlements = [
    {label: 'TD01', value: 'TD01', checked: false},
    {label: 'AC01', value: 'AC01', checked: false},
    {label: 'AE01', value: 'AE01', checked: false},
    {label: 'EP01', value: 'EP01', checked: false},
    {label: 'DP01', value: 'DP01', checked: false}
  ]
  fields = {
    Report: '1'
  }

  constructor(
    public pageService: PageService,
    public route: ActivatedRoute,
    private messageService: NzMessageService,
    private commonAcquirerService: CommonAcquirerService,
    private acquirerService: AcquirerService,
    private i18n: I18NService,
  ) {
    super(pageService, route)
  }

  ngOnInit(): void {
    this.initialData()
  }

  initialData() {
    this.commonAcquirerService.viewAcquirer$.value$.subscribe(acquirer => {
      // Reset columns
      this.initialColumns()

      this.data = deepCopy(acquirer.institution.common.settleInfo)
      this.params.version = acquirer.institution.version
      this.setSettlements()
      this.setEdit(this.fields.Report, 1)
      this.setupReportColumns()
      this.setupIdForColumn(this.fields)
    })
    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  setSettlements() {
    const { reportList } = this.data
    if (!reportList) {
      return
    }
    this.settlements.map(settlement => {
      settlement.checked = reportList.includes(settlement.value)
    })
  }

  setupReportColumns(): void {
    this.columns[this.fields.Report].push([
      {
        span: 20,
        label: 'GENERAL.INFO.REPORTS_REQUIRED',
        labelI18n: 'GENERAL.INFO.REPORTS_REQUIRED',
        template: this.chkSettlement,
        index: 'reportList',
        value: this.data.reportList,
        displayValue: this.renderSettlement()
      },
      {
        span: 4,
        label: 'GENERAL.INFO.OPERATION',
        labelI18n: 'GENERAL.INFO.OPERATION',
        operate: true,
        template: this.settleOperate,
        acl: ['api.put.camel.institution.one.settlement'],
      }
    ])
  }

  renderSettlement(): string {
    return this.settlements.filter(settle => settle.checked).map(settle => settle.label).join(',')
  }

  // abstract methods
  onCancel() {
    // If user cancel the edit, the value should retain as initial value.
    this.setSettlements()
  }

  onSubmit() {
    try {
      this.columns[this.field][this.rowIndex].forEach(column => {
        if (!column.index) return
        column.displayValue = this.renderSettlement()
        if (column.index === 'reportList') {
          this.data.reportList = this.settlements.filter(settle => settle.checked === true).map(settle => settle.value)
        }
      })
      this.params.settlement = this.data

      const insCode = this.getID()
      this.acquirerService.updateSettlementAcquirer(this.params, insCode).subscribe(
        acquirer => {
          this.commonAcquirerService.setViewingAcquirer(acquirer)
          this.messageService.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
        },
        err => {
          const { error } = err
          this.messageService.error(error.msg)
          this.initialData()
        }
      )
    } catch (error) {
      this.messageService.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'))
    }

  }

  initialColumns() {
    /*
    * 这个columns是用来收集所有需要display在这个tab里面的数据.
    * 比如 "交易币种转换" = '1', 然后交易币种转换里有一个Array = [商户交易币种, 转换交易币种, 转换汇率, 等等] 然后他在columns里就是
    * {'1': [[{商户交易币种, 转换交易币种, 转换汇率, 等等}]]}
    */
    // 现在这个trades component需要展示2个field. 这里创建2个空的Array在this.columns里的field
    for (const key in this.fields) {
      this.columns[this.fields[key]] = []
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
